Sub CreateCharts()
    Dim ws As Worksheet
    Dim chart As ChartObject
    Dim lastRow As Long
    Dim chartRange As Range
    Dim chartTitle As String
    Dim chartTemplate As String
    Dim chartLeft As Double
    Dim chartTop As Double
    Dim rowNum As Integer
    Dim colNum As Integer
    Dim chartPosition As Range
    Dim chartSize As Range
    
    ' 전체영업이익 시트를 지정
    Set ws = ThisWorkbook.Sheets("전체영업이익")
    
    ' 차트 서식 파일 경로 설정
    chartTemplate = "D:\추세차트.crtx"
    
    ' 각 시트를 순차적으로 돌며 차트 생성
    For Each Sheet In ThisWorkbook.Sheets
        ' 전체영업이익 시트는 제외
        If Sheet.Name <> "전체영업이익" Then
            ' 데이터 범위 설정 (B열: 날짜, G열: 영업이익, H열: 전년도 영업이익)
            lastRow = Sheet.Cells(Rows.Count, "B").End(xlUp).Row
            Set chartRange = Sheet.Range("B4:B" & lastRow & ", G4:G" & lastRow & ", H4:H" & lastRow)
            
            ' 차트 제목 설정 (시트의 B2 셀 텍스트 사용)
            chartTitle = Sheet.Range("B2").Value
            
            ' 차트 배치 위치 계산
            colNum = (ThisWorkbook.Sheets("전체영업이익").ChartObjects.Count) Mod 4
            rowNum = Int((ThisWorkbook.Sheets("전체영업이익").ChartObjects.Count) / 4) * 9 + 1
            
            ' 차트 배치 위치 및 크기 계산
            Set chartPosition = ws.Range(ws.Cells(rowNum, colNum * 5 + 1), ws.Cells(rowNum + 8, colNum * 5 + 5))
            Set chartSize = chartPosition

            ' 차트 추가
            Set chart = ws.ChartObjects.Add(Left:=chartSize.Left, Top:=chartSize.Top, Width:=chartSize.Width, Height:=chartSize.Height)
            
            ' 차트 데이터 설정
            chart.chart.SetSourceData Source:=chartRange
            
            ' 차트 서식 적용
            chart.chart.ApplyChartTemplate (chartTemplate)
            
            ' 차트 제목 설정
            chart.chart.HasTitle = True
            chart.chart.chartTitle.Text = chartTitle
        End If
    Next Sheet
End Sub